﻿using Castle.DynamicProxy;
using Extensions.Attributes;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace Extensions.AopInterceptors
{
    public class BaseCacheAOP : CacheAOPBase
    {
        private readonly IDistributedCache cache;
        public BaseCacheAOP(IDistributedCache cache)
        {
            this.cache = cache;
        }
        public override void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;
            if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute cachingAttribute)
            {

                var cacheKey = GetCacheKey(invocation);
                var cacheValue = cache.GetString(cacheKey);
                if (cacheValue != null)
                {
                    invocation.ReturnValue = JsonConvert.DeserializeObject(cacheValue, method.ReturnType);
                    return;
                }
                invocation.Proceed();
                if (!string.IsNullOrWhiteSpace(cacheKey))
                {

                    cache.SetString(cacheKey, JsonConvert.SerializeObject(invocation.ReturnValue), new DistributedCacheEntryOptions
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(cachingAttribute.AbsoluteExpirationReleativeToNow)
                    });
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
